//
//  BMSAuthSDK.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSAuthSDK.h"
#import "BMSAuthManager.h"
#import "BMSAPIService.h"
#import "BMSInitializer.h"
#import "BMSPopupQueueManager.h"
#import "BMSPrivacyExitView.h"
#import "BMSDeviceInfo.h"
#import "BMSAppInfoHelper.h"
#import "BMSPrivate.h"
#import "BMSKeychain.h"
#import "BMSLinkOpener.h"
#import "BMSVibrator.h"

@interface BMSAuthSDK()

@end

static BMSAuthSDK *instance = nil;

@implementation BMSAuthSDK

+ (BMSAuthSDK *)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BMSAuthSDK alloc]init];
    });
    return instance;
}

#pragma mark ------------ public method -----------

-(void)checkIPBlockStatusWithAppName:(NSString *)appName channel:(NSString *)channel version:(NSString *)version ip:(NSString *)ip success:(void (^)(NSDictionary * _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure {
    [BMSAPIService checkIPBlockStatusWithAppName:appName channel:channel version:version ip:ip success:success failure:failure];
}

- (void)fetchOfficialHolidaysWithSuccess:(void (^)(id _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure {
    [BMSAPIService fetchOfficialHolidaysWithSuccess:success failure:failure];
}

- (void)initSDKCompletion:(BMSInitCompletion)completion {
    [BMSInitializer shared].appName = [BMSAppInfoHelper bmsAppNameForInfoPlistFile];
    [BMSInitializer shared].version = [BMSAppInfoHelper bmsAppVersionForInfoPlistFile];
    [BMSInitializer shared].channel = [BMSAppInfoHelper bmsChannelForSDKConfigFile];

    [BMSInitializer startWithAppName:[BMSInitializer shared].appName version:[BMSInitializer shared].version channel:[BMSInitializer shared].channel completion:^{
        
        // ✅ Step 1: 隐私合规弹窗
        if (![BMSInitializer shared].didAgreePrivacy &&
            [BMSInitializer shared].launchModel.openPri == 1) {
            
            BMSAuthManager *manager = [[BMSAuthManager alloc] init];
            [manager showPrivacyPopupWithCompletion:^(BOOL agreed) {
                [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_BASE_PRIVACY_CLICK description:BMS_WDS_PRIVACY_POPUP_ACTION tab1:[NSString stringWithFormat:@"%id",agreed] tab2:@"" tab3:@"" tabN:@{}]];
                if (agreed) {
                    
                    // ✅ Step 2: 登录并获取 UUID、IDFA 状态
                    [[BMSInitializer shared] handlePrivacyAgreedAndLoginWithCompletion:^(BOOL loginSuccess) {
                        
                        // ✅ Step 3: 根据配置决定是否实名
                        [self handleRealnameIfNeededWithCompletion:^(BOOL didRealname) {
                            if (completion) {
                                completion(loginSuccess,
                                           YES,
                                           [BMSInitializer shared].idfaAuthorized,
                                           didRealname,
                                           [BMSInitializer shared].uuid);
                            }
                        }];
                    }];
                } else {
                    // ❌ 拒绝隐私协议，尝试弹退出或实名（按产品要求）
                    BMSAuthManager *exitManager = [[BMSAuthManager alloc] init];
                    [exitManager showExitPopupWithCompletion:^(BOOL retry) {
                        if (retry &&
                            [BMSInitializer shared].launchModel.rnAuthApi == 1) {
                            [[BMSInitializer shared] handlePrivacyAgreedAndLoginWithCompletion:^(BOOL loginSuccess) {
                                
                                // ✅ Step 3: 根据配置决定是否实名
                                [self handleRealnameIfNeededWithCompletion:^(BOOL didRealname) {
                                    if (completion) {
                                        completion(loginSuccess,
                                                   YES,
                                                   [BMSInitializer shared].idfaAuthorized,
                                                   didRealname,
                                                   [BMSInitializer shared].uuid);
                                    }
                                }];
                            }];
                        }
                        if (completion) {
                            completion(YES, YES, NO, NO, [BMSKeychain WDKeychainGetUUID]);
                        }
                    }];
                    
                }
            }];
        } else {
            // ✅ 已同意隐私
            [[BMSInitializer shared] handlePrivacyAgreedAndLoginWithCompletion:^(BOOL loginSuccess) {
                [self handleRealnameIfNeededWithCompletion:^(BOOL didRealname) {
                    if (completion) {
                        completion(loginSuccess,
                                   YES,
                                   [BMSInitializer shared].idfaAuthorized,
                                   didRealname,
                                   [BMSInitializer shared].uuid);
                    }
                }];
            }];
            NSLog(@"已同意隐私未实名");
        }
    }];
}

-(void)showPrivacyPopupWithCompletion:(void (^)(BOOL))completion {
    BMSAuthManager *manager = [[BMSAuthManager alloc]init];
    [manager showPrivacyPopupWithCompletion:^(BOOL agreed) {
        
    }];
}

- (void)showRealnamePopupWithCompletion:(void (^)(BOOL success))completion {
    BMSAuthManager *manager = [[BMSAuthManager alloc]init];
    [manager showRealnamePopupWithCompletion:^(BOOL success) {
        completion(success);
    }];
}

- (NSString *)BMSUUID {
    return [BMSInitializer shared].loginModel.uuid ? [BMSInitializer shared].loginModel.uuid : [[BMSDeviceInfo shared]UUID];
}

- (void)openTerms {
    [BMSLinkOpener openTerms];
}

- (void)openPrivacy {
    [BMSLinkOpener openPrivacy];
}

/// 单次震动，默认样式（短促）
- (void)vibrateOnce {
    [BMSVibrator vibrateOnce];
}

/// 自定义震动（使用 CoreHaptics 模拟间隔+时长震动）
- (void)vibrateWithPattern:(NSArray<NSNumber *> *)pattern
                    repeat:(NSInteger)repeat {
    [BMSVibrator vibrateWithPattern:pattern repeat:repeat];
    
}

/// 取消震动（如果可取消）
- (void)vibrateCancel {
    [BMSVibrator vibrateCancel];
}


- (void)handleRealnameIfNeededWithCompletion:(void(^)(BOOL didRealname))completion {
    [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_REALNAME_JSON description:BMS_WDS_REALNAME_CONFIG_FETCH tab1:[NSString stringWithFormat:@"%d",[BMSInitializer shared].launchModel.rnAuth] tab2:@"" tab3:@"" tabN:@{}]];
    if ([BMSInitializer shared].didRealnameAuth) {
        if (completion) completion(YES);
        return;
    }

    if ([BMSInitializer shared].launchModel.rnAuth == 1) {
        // 不强制实名
        if (completion) completion(NO);
        return;
    }

    // 需要实名弹窗
    BMSAuthManager *manager = [[BMSAuthManager alloc] init];
    [manager showRealnamePopupWithCompletion:^(BOOL success) {
        if (completion) {
            completion([BMSInitializer shared].didRealnameAuth);
        }

        if (!success) {
            // ⚠️ 可选处理：退出、提示、记录日志等
            NSLog(@"[BMS] 用户实名失败或取消");
        }
    }];
}

@end
